package com.laiat.yamba.activity;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.laiat.yamba.Manifest;
import com.laiat.yamba.YambaApplication;

public class PrepareRequestTokenActivity extends Activity  {
	private static final String TAG = PrepareRequestTokenActivity.class.getSimpleName();

	private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
	private static final String ACCESS_URL = "https://api.twitter.com/oauth/access_token";
	private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";

	public static final String	OAUTH_CALLBACK_SCHEME	= "x-oauthflow";
	public static final String	OAUTH_CALLBACK_HOST		= "callback";
	public static final String	OAUTH_CALLBACK_URL		= OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
	
	private OAuthConsumer consumer;
	private OAuthProvider provider;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	   	try {
	   		System.setProperty("debug", "true");
	   		
	   		YambaApplication yamba = (YambaApplication)getApplication();
			String consumerKey = yamba.getConsumerKey();
	        String consumerSecret = yamba.getConsumerSecret();
	        
	   		this.consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	   		this.provider = new CommonsHttpOAuthProvider(
	   	        		REQUEST_URL/*  + "?scope=" + URLEncoder.encode(Constants.SCOPE, Constants.ENCODING)*/,
	   	        		ACCESS_URL,
	   	        		AUTHORIZE_URL);

	   	} catch (Exception e) {
	   		Log.e(TAG, "Error creating consumer / provider",e);

	   		Toast.makeText(this, "Error in Twitter Login", Toast.LENGTH_LONG);
	   	}

	   	Log.i(TAG, "Starting task to retrieve request token.");
	   	new OAuthRequestTokenTask(this,consumer,provider).execute();
	}
	
	
	//Async post to twitter
	class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
		private static final String TAG = "OAuthRequestTokenTask";

		private Context context;
		private OAuthConsumer consumer;
		private OAuthProvider provider;
		
		//called to initiate background activity
		public OAuthRequestTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider) {
			super();
			this.context = context;
			this.consumer = consumer;
			this.provider = provider;
		}

		/**
		 * 
		 * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
		 * 
		 */
		@Override
		protected Void doInBackground(Void... params) {

			try {
				Log.i(TAG, "Retrieving request token from twitter servers");
				final String url = provider.retrieveRequestToken(consumer, OAUTH_CALLBACK_URL);
				Log.i(TAG, "Popping a browser with the authorize URL : " + url);
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
				context.startActivity(intent);

			} catch (Exception e) {
				Log.e(TAG, "Error during OAUth retrieve request token", e);

				//send error message
				Intent intent = new Intent(YambaApplication.BROADCAST_TWITTER_RESULT);
		   		intent.putExtra(YambaApplication.OAUTH_TEXT, "Error in Twitter Login - request token");
				intent.putExtra(YambaApplication.OAUTH_LOGIN_EXCEPTION, e);
				
				context.sendBroadcast(intent, Manifest.permission.RECEIVE_TWITTER_RESULT);
			}

			return null;
		}
		
	}
	
	
	/**
	 * Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
	 * The callback URL will be intercepted here.
	 */
	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Uri uri = intent.getData();
		if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
			Log.i(TAG, "Callback received : " + uri);
			Log.i(TAG, "Retrieving Access Token");
			new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
			finish();
		}
	}

	public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
	
		private static final String TAG = "RetrieveAccessTokenTask";
		
		private Context context;
		private OAuthConsumer consumer;
		private OAuthProvider provider;
		private SharedPreferences prefs;
		
		//called to initiate background activity
		public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider, SharedPreferences prefs) {
			super();
			this.context = context;
			this.consumer = consumer;
			this.provider = provider;
			this.prefs = prefs;
		}

		
		
		/**
		 * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
		 * for future API calls.
		 */
		@Override
		protected Void doInBackground(Uri...params) {
			final Uri uri = params[0];

			final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

			try {
				provider.retrieveAccessToken(consumer, oauth_verifier);

				final Editor edit = prefs.edit();
				edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
				edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
				edit.commit();

				//FIXME:  change to go to last activity in yamba
				//use ActivityManager.getRecentTask ?? and  android.permission.GET_TASKS
//				context.startActivity(new Intent(context, StatusActivity.class));

				Log.i(TAG, "OAUTH STAGE TWO OK!");

			} catch (Exception e) {
				Log.e(TAG, "OAUTH STAGE TWO ERROR", e);
				
				//send error message
				Intent intent = new Intent(YambaApplication.BROADCAST_TWITTER_RESULT);
		   		intent.putExtra(YambaApplication.OAUTH_TEXT, "Error in Twitter Login - Stage 2");
				intent.putExtra(YambaApplication.OAUTH_LOGIN_EXCEPTION, e);
				
				context.sendBroadcast(intent, Manifest.permission.RECEIVE_TWITTER_RESULT);
			}

			return null;
		}

	}
	
}

